import { navigateTo, showToast, getStorageSync, setStorageSync } from '../../utils/handlers'
import { instanceDefaultHandler, instanceDefaultData } from '../../utils/instanceDefaultProperty'
import { postTabs, postIndexList, postWechatPhoneNumber, postEntryPhone, postLog } from '../../utils/request'
import { APPID, APPSECRET } from '../../utils/globalData'

const APP = getApp();
const globalData = APP.globalData;
const loginPromise = globalData.loginPromise;

const defaultData = {
    swiperSetting: {
        indicatorDots: true,
        indicatorColor: '#d8dce8',
        indicatorActiveColor: '#ff0000',
        autoplay: true,
    },
    search: {
        longitude: 0,
        latitude: 0
    },
    storeList: {
        pageNo: 0,
        pageSize: 10,
        dtoList: []
    },
    hasPullDownRefresh: true,
    isShowPhoneLogin: false,
    isShowSearch: false,
    searchStoreList: {
        pageNo: 0,
        pageSize: 10,
        dtoList: []
    },
    isShowSearchRestaurantList: true,
    isSearchEmpty: false,
    hotSearch: [],
    searchHistory: [],
    searchValue: '',
    searchInputFocus: false,
    location: '广州'
};

const renderHandlers = {
    onPostIndexListSuccess: function (res) {
        const { storeList: prevStoreList } = this.data;
        const { code, data } = res;
        const { bannerList, storeList } = data.t;
        if (this.data.hasPullDownRefresh) wx.stopPullDownRefresh();
        let isShowPhoneLogin = false;
        if (globalData.loginInfo.hasPhoneLogin === 1) isShowPhoneLogin = true;
        if (code === 6666) {
            if (storeList.dtoList.length === 0) {
                if (prevStoreList.dtoList.length === 0) showToast({ title: '附近暂无商铺' });
                this.setData({
                    bannerList,
                    isShowPhoneLogin
                });
                return
            }
            storeList.dtoList.map(item => {
                item.distanc = Math.ceil(item.distanc)
            });
            this.setData({
                bannerList,
                storeList: {
                    ...storeList,
                    dtoList: prevStoreList.pageNo === 0 ? storeList.dtoList : prevStoreList.dtoList.concat(storeList.dtoList)
                },
                isShowPhoneLogin
            })
        }
    },
    renderIndexList: function () {
        const { storeList } = this.data;
        const { pageNo, pageSize } = storeList;
        postIndexList({
            isEnCode: false,
            success: (res) => {
                globalData.tabPromise.then((tabListCp) => {
                    this.onPostIndexListSuccess(res, tabListCp)
                })
            }
        }, {
            pageNo: pageNo + 1,
            pageSize: pageSize,
            search: globalData.location
        })
    },
    renderTabbar: function (tabList, resolve) {
        let tabListCp = JSON.parse(JSON.stringify(tabList));
        tabListCp = tabListCp.map(item => {
            let isCurrent = item.tabType !== '300';
            return {
                ...item,
                isCurrent
            }
        });
        let indexTabType = tabListCp[tabListCp.findIndex(item => item.isCurrent)].tabType;
        this.setData({
            indexTabType,
            tabList: tabListCp
        }, () => {
            resolve && resolve(tabListCp)
        })
    },
    renderSearchHistory: function () {
        const searchHistory = getStorageSync('searchHistory') || [];
        this.setData({
            isShowSearchRestaurantList: false,
            searchHistory
        })
    }
};

const searchHandlers = {
    renderSearchList: function (isNewSearch) {
        const { searchStoreList, searchValue, isShowSearchRestaurantList } = this.data;
        const { pageNo, pageSize } = searchStoreList;
        postIndexList({
            isEnCode: false,
            loading: isShowSearchRestaurantList,
            success: (res) => {
                const { searchStoreList: prevSearchStoreList } = this.data;
                const { code, data } = res;
                const { storeList } = data.t;
                if (this.data.hasPullDownRefresh) wx.stopPullDownRefresh();
                if (code === 6666) {
                    if (storeList.dtoList.length === 0) {
                        if (isNewSearch) { // 修改搜索关键词的情况
                        } else { // 下拉加载更多的情况
                            showToast({ title: '没有更多的搜索结果' })
                        }
                        return
                    }
                    storeList.dtoList.map(item => {
                        item.distanc = Math.ceil(item.distanc)
                    });
                    this.setData({
                        isSearchEmpty: false,
                        searchStoreList: {
                            ...storeList,
                            dtoList: prevSearchStoreList.pageNo === 0 ? storeList.dtoList : prevSearchStoreList.dtoList.concat(storeList.dtoList)
                        }
                    })
                }
            }
        }, {
            pageNo: pageNo + 1,
            pageSize: pageSize,
            search: {
                ...globalData.location,
                storeName: searchValue
            }
        })
    },
    clearSearchHistory: function () {
        const searchHistory = [];
        setStorageSync('searchHistory', searchHistory);
        this.setData({ searchHistory })
    },
    addSearchHistory: function (value) {
        let searchHistory = getStorageSync('searchHistory') || [];
        const index = searchHistory.indexOf(value);
        if (index === -1) {
            searchHistory.unshift(value);
        } else {
            searchHistory.splice(index, 1);
            searchHistory.unshift(value);
        }
        searchHistory = searchHistory.slice(0, 10);
        setStorageSync('searchHistory', searchHistory);
        this.setData({ searchHistory })
    },
    bindTapRecommendItem: function (e) {
        const { value } = e.currentTarget.dataset;
        const simulateEventObject = {
            detail: {
                value
            }
        };
        this.bindInputSearch(simulateEventObject)
    },
    bindClearSearchValue: function () {
        this.setData({
            isShowSearchRestaurantList: false,
            isSearchEmpty: false,
            searchValue: '',
            searchStoreList: {
                pageNo: 0,
                pageSize: 10,
                dtoList: []
            }
        });
    },
    bindInputSearch: function (e) {
        const { value } = e.detail;
        let { debounceID } = this.data;
        if (debounceID) clearTimeout(debounceID);
        if (!value) {
            this.bindClearSearchValue();
            return
        }
        debounceID = setTimeout(() => {
            this.renderSearchList(true);
            this.addSearchHistory(value);
        }, 1000);
        this.setData({
            isSearchEmpty: false,
            isShowSearchRestaurantList: false,
            debounceID,
            searchValue: value,
            searchStoreList: {
                pageNo: 0,
                pageSize: 10,
                dtoList: []
            }
        });
    },
    bindConfirmSearch: function (e) {
        const { searchStoreList } = this.data;
        if (searchStoreList.dtoList.length === 0) {
            this.setData({
                isShowSearchRestaurantList: true,
                isSearchEmpty: true,
                searchStoreList: {
                    pageNo: 0,
                    pageSize: 10,
                    dtoList: this.data.storeList.dtoList.slice(0, 5)
                }
            });
            return;
        }
        this.setData({
            isShowSearchRestaurantList: true
        })
    },
    bindShowSearch: function () {
        const { searchValue } = this.data;
        this.setData({
            isShowSearch: true,
            searchInputFocus: true
        });
        if (!searchValue) {
            this.renderSearchHistory()
        }
    },
    bindCancelSearch: function () {
        const { isSearchEmpty } = this.data;
        this.setData({
            isShowSearch: false,
            searchInputFocus: false
        });
        if (isSearchEmpty) {
            this.bindClearSearchValue()
        }
    }
};

const handlers = {
    bindgetphonenumber: function (e) {
        const { errMsg, encryptedData, iv } = e.detail;
        loginPromise.then(loginInfoFromResolve => {
            console.log('page: index, bindgetphonenumber => loginInfoFromResolve:');
            console.log(loginInfoFromResolve);
            if (errMsg === "getPhoneNumber:ok") {
                this.setData({
                    hadAuth: true
                });
                if (!loginInfoFromResolve.loginedUser.phoneNo) {
                    wx.login({
                        success: LoginRes => {
                            postWechatPhoneNumber({
                                success: res => {
                                    console.log('page: index, postWechatPhoneNumber（绑定手机号接口） => res:');
                                    console.log(res)
                                }
                            }, {
                                appid: APPID,
                                secret: APPSECRET,
                                encryptedData,
                                iv,
                                jsCode: LoginRes.code
                            })
                        }
                    });
                }
            }
        })
    },
    bindRegister: function () {
        postLog({
            isEnCode: false,
            success: res => {
                console.log(res)
            }
        }, { resource: '800002' });
        navigateTo({
            url: '/pages/register/intro/intro'
        })
    },
    bindTapRestaurant: function (e) {
        const { storeid, isappoint } = e.currentTarget.dataset;
        navigateTo({
            url: '/pages/customer/list/list'
        }, { storeId: storeid, isAppoint: isappoint })
    },
    bindTapPhoneLogin: function () {
        navigateTo({
            url: '/pages/phoneLogin/phoneLogin'
        })
    }
};

Page({
    data: {
        ...instanceDefaultData,
        ...defaultData
    },

    ...instanceDefaultHandler,

    ...renderHandlers,
    ...searchHandlers,
    ...handlers,

    onLoad: function () {
        let phoneNo = getStorageSync('phone');
        if (phoneNo) {
            this.setData({
                hadAuth: true
            })
        }
        this.renderSearchHistory();
    },

    onShow: function () {
        let tabPromise = null;
        if (globalData.tabList) {
            this.renderTabbar(globalData.tabList)
        } else {
            tabPromise = new Promise(resolve => {
                postTabs({
                    isEnCode: false,
                    success: res => {
                        const { code, data } = res;
                        if (code === 6666) {
                            globalData.tabList = data.tabList;
                            this.renderTabbar(data.tabList, resolve)
                        }
                    }
                })
            });
            globalData.tabPromise = tabPromise;
        }
        wx.getLocation({
            type: 'gcj02',
            success: res => {
                APP.QQMapWX.reverseGeocoder({
                    location: {
                        longitude: res.longitude,
                        latitude: res.latitude
                    },
                    success: res => {
                        const location__city = res.result.address_component.city;
                        globalData.location__city = location__city;
                        location__city && this.setData({
                            location: location__city
                        })
                    }
                });
                globalData.location = {
                    longitude: res.longitude,
                    latitude: res.latitude
                };
                this.renderIndexList()
            },
            fail: res => {
                showToast({ title: '获取地址位置失败' })
            }
        });
    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {
        const { isShowSearch } = this.data;
        if (isShowSearch) {
            wx.stopPullDownRefresh();
        } else {
            this.setData({
                'storeList.pageNo': 0
            }, () => {
                this.renderIndexList()
            });
        }
    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {
        const { isShowSearch, isShowSearchRestaurantList, isSearchEmpty } = this.data;
        if (isShowSearch) {
            if (isShowSearchRestaurantList && !isSearchEmpty) {
                this.renderSearchList(false)
            }
        } else {
            this.renderIndexList()
        }
    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {
    }
});